﻿#region Copyright notice and license

// Copyright 2019 The gRPC Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#endregion

using System.Net;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;

namespace Common;

public static class BenchmarkConfigurationHelpers
{
    public static BindingAddress CreateBindingAddress(this IConfiguration config)
    {
        var url = config["server.urls"] ?? config["urls"];

        if (string.IsNullOrEmpty(url))
        {
            return BindingAddress.Parse("http://localhost:5000");
        }

        return BindingAddress.Parse(url);
    }

    public static IPEndPoint CreateIPEndPoint(this IConfiguration config)
    {
        var address = config.CreateBindingAddress();

        IPAddress? ip;

        if (string.Equals(address.Host, "localhost", StringComparison.OrdinalIgnoreCase))
        {
            ip = IPAddress.Loopback;
        }
        else if (!IPAddress.TryParse(address.Host, out ip))
        {
            ip = IPAddress.IPv6Any;
        }

        return new IPEndPoint(ip, address.Port);
    }
}
